/*
Copyright (c) 2010 Neil Wood

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package  envisage.Controls
{
	import envisage.Data.IArray;
	import envisage.Data.UIArrayEvent;
	import Util.Utils;
	
	import flash.display.DisplayObject;
	import flash.display.Shape;
	import flash.utils.getDefinitionByName;
	
	public class ArraySubset extends Control
	{
		public function ArraySubset()
		{
			super();
			
			NoScale = true;	
			
			shapeMask = new Shape();
			addChild(shapeMask);
			this.mask = shapeMask;
			UpdateMask();
		}
		
		protected override function Layout():void
		{
			UpdateMask();
		}
		
		private var shapeMask:Shape;
		protected function UpdateMask():void
		{
			shapeMask.graphics.clear();
			shapeMask.graphics.beginFill(0x000000, 1);
			shapeMask.graphics.drawRect(0, 0, width, height);
			shapeMask.graphics.endFill();
		} 
		
		private var iArray:IArray;
		public function get DataArray():IArray { return iArray; }
		public function set DataArray(value:IArray):void
		{
			if( iArray != null )
			{
				iArray.removeEventListener(UIArrayEvent.ITEM_INSERTED, ItemInserted);
				iArray.removeEventListener(UIArrayEvent.ITEM_REMOVED,  ItemRemoved);
				iArray.removeEventListener(UIArrayEvent.ITEM_UPDATED,  ItemUpdated);
				iArray.removeEventListener(UIArrayEvent.ITEMS_REARRANGED, ItemsRearranged);
				iArray.removeEventListener(UIArrayEvent.ITEMS_REPLACED, ItemsReplaced);
			}
			
			iArray = value;
			
			if( iArray != null )
			{
				iArray.addEventListener(UIArrayEvent.ITEM_INSERTED, ItemInserted);
				iArray.addEventListener(UIArrayEvent.ITEM_REMOVED,  ItemRemoved);
				iArray.addEventListener(UIArrayEvent.ITEM_UPDATED,  ItemUpdated);
				iArray.addEventListener(UIArrayEvent.ITEMS_REARRANGED, ItemsRearranged);
				iArray.addEventListener(UIArrayEvent.ITEMS_REPLACED, ItemsReplaced);
			}
			
			SetVisibleItemsLength(0);
			
			fRequireUpdate();
		}

		private function RequireItem(pos:int, index:int):void
		{
			if( arrControls[pos] != null ) throw "";
			
			if( index >= iArray.GetNumItems() ) arrControls[pos] = null;
			
			else
			{
				var c:DisplayObject;
				if( stackTempItems.length == 0 )
				{
					var itemclass:Class = Class(getDefinitionByName(strItemClassName));
					c = new itemclass();
				}
				
				else c = stackTempItems.pop();
				
				addChild(c);
				arrControls[pos] = c;
				
				fModify(c, iArray.GetItem(index), owner);
				
				//var c:DisplayObject = fCreateItem(iArray.GetItem(index));
				//addChild(c);
				//arrControls[pos] = c;
			}
		}
	
		private function UnrequireItem(pos:int):void
		{
			var c:DisplayObject = arrControls[pos] as DisplayObject;
			
			if( c == null ) return;
			
			removeChild(c);
			
			arrControls[pos] = null;
			
			stackTempItems.push(c);
		}
		
		public function ItemsRearranged(e:UIArrayEvent):void
		{
			SetVisibleItemsLength(0);
			fRequireUpdate();
		}
		
		public function ItemsReplaced(e:UIArrayEvent):void
		{
			//ClearAllSelections();
			SetVisibleItemsLength(0);
			fRequireUpdate();
		}
		
		public function ItemInserted(e:UIArrayEvent):void
		{
			SetVisibleItemsLength(0);
			fRequireUpdate();
		}
		
		public function ItemRemoved(e:UIArrayEvent):void
		{
			//Deselect item
			//ClearAllSelections();
			SetVisibleItemsLength(0);
			fRequireUpdate();
		}
		
		public function ItemUpdated(e:UIArrayEvent):void
		{
			SetVisibleItemsLength(0);
			fRequireUpdate();
		}
		
		public function ControlFromObject(item:Object):DisplayObject
		{
			for(var i:int = topIndex ; i < topIndex + arrControls.length ; i++)
				if( DataArray.GetItem(i) == item )
					return GetControl(i);
					
			return null;
		}
		
		///////////////////////////////////////////////////////////////////////////////////
		
		private var arrControls:Array    = new Array()	//Array to hold the subset of items.
		private var topPos:int   = 0			//index in above array that holds the first item. (this acts as a circular array which is good for scrolling)
		private var topIndex:int = 0;			//index into larger array that the first item of above array represents.
		
		public function GetControl(index:int):DisplayObject //Get item at index into larger array, or throw error.
		{
			if( index < topIndex ) throw "";
			if( index >= topIndex + arrControls.length ) throw "";
			
			var i:int = topPos + (index-topIndex);
			i %= arrControls.length;
			
			return arrControls[i];	
		}
		
	
		//Set the current large index to one less than its current value.
		private function DecTopIndex():void
		{
			topPos--;
			if( topPos < 0 ) topPos = arrControls.length-1;
			UnrequireItem(topPos);
			topIndex--;
			RequireItem(topPos, topIndex);
			
		}
		
		//Set the current large index to one more than its current value.
		private function IncTopIndex():void
		{
			UnrequireItem(topPos);
			RequireItem(topPos, topIndex+arrControls.length);
			topIndex++;
			topPos++;
			if( topPos >= arrControls.length ) topPos = 0; 
		}
		
		public function GetVisibleItemTopIndex():int
		{
			return topIndex;
		}
		
		public function GetVisibleItem(index:int):DisplayObject
		{
			if( index < topIndex ) throw "";
			if( index >= topIndex + arrControls.length ) throw "";
			
			var i:int = topPos + (index-topIndex);
			i %= arrControls.length;
			
			return arrControls[i];	
		}
		
		//Set the first index of the subset.
		public function SetVisibleItemsTopIndex(topIndex:int):void
		{
			if( topIndex < 0 ) topIndex = 0;
			
			var dif:int = topIndex-this.topIndex;
			if( dif > arrControls.length || dif < -arrControls.length )
			{
				this.topIndex = topIndex;
				this.topPos = 0;
				for(i = 0 ; i < arrControls.length ; i++) UnrequireItem(i);
				for(i = 0 ; i < arrControls.length ; i++) RequireItem(i, topIndex+i);
			}
			
			else
			{
				for(var i:int = 0 ; i < Math.abs(dif) ; i++)
					if( dif > 0 ) IncTopIndex(); else DecTopIndex();
			}
		}
		
		public function GetVisibleItemsLength():int { return arrControls.length; }
		
		//Set the number of items in the subset
		public function SetVisibleItemsLength(len:int):void
		{
			if( len < 0 ) len = 0;
			
			var i:int;
			var dif:int = len - arrControls.length;
			
			if( dif > 0 )
			{
				for(i = 0 ; i < dif ; i++)
				{
					Utils.ArrayInsertIndex(arrControls, topPos, null);
					RequireItem(topPos, topIndex + arrControls.length-1);
					topPos++;
					if( topPos >= arrControls.length ) topPos = 0;
				}
			}
			
			else if( len < arrControls.length )
			{
				for(i = 0 ; i < -dif ; i++)
				{
					topPos--;
					if( topPos == -1 ) topPos = arrControls.length-1;
					UnrequireItem(topPos);
					Utils.ArrayDeleteIndex(arrControls, topPos);
				}
			}
		}
		
		private var stackTempItems:Array = new Array();

		/////////////////////////////////////////////////////////////////////
		private var strItemClassName:String;
		public function set itemClassName(value:String):void { this.strItemClassName = value; }
		public function get itemClassName():String { return strItemClassName; }
		
		private var fModify:Function;
		public function set modify(value:Function):void { this.fModify = value; }
		public function get modify():Function { return fModify; }
		//private var fCreateItem:Function;
		//private var fDiscardItem:Function;
		
		//public function set createItem(value:Function):void { this.fCreateItem = value; }
		//public function set discardItem(value:Function):void { this.fDiscardItem = value; }
		
		private var fRequireUpdate:Function;
		public function set requireUpdate(value:Function):void{ this.fRequireUpdate = value; }
		
		private var owner:Object;
		public function set Owner(value:Object):void { this.owner = value; }
		
		private var arrSelected:Array = new Array();
		
		public function GetSelected():Array { return arrSelected; }
		
		public function SetItemSelected(item:Object, selected:Boolean):Boolean
		{
			var i:int = arrSelected.indexOf(item);
		
			if( (selected == true && i != -1) 
			||  (selected == false && i == -1 ) ) return false;
			
			if( selected ) arrSelected.push(item);
			else Utils.ArrayDeleteIndex(arrSelected, i); 
			
			return true;
		}
		
		public function GetItemSelected(item:Object):Boolean
		{
			return arrSelected.indexOf(item) != -1;
		}		
		
		public function ClearAllSelections():void
		{//still not quite right as list should send out message?
		trace("Clear all selections");
			arrSelected.length = 0;
		}
		
		public function InvalidateItem(index:int):void
		{
			fModify(GetVisibleItem(index), iArray.GetItem(index), owner);
		}
	}
}


/*leftover from arraysubset
		//Return the first index into larger array currently held.
		public function GetTopIndex():int
		{
			return topIndex;
		}
		
		//Get item at index into larger array, or throw error.
		public function GetItem(index:int):Control
		{
			if( index < topIndex ) throw "";
			if( index >= topIndex + arr.length ) throw "";
			
			var i:int = topPos + (index-topIndex);
			i %= arr.length;
			
			return arr[i];	
		}*/
		
		
		/*
		//Get the number of items currently in the subset.
		//public function GetLength():int { return arr.length; }
*/

